﻿using System;
using System.Deployment.Application;
using System.Threading.Tasks;

namespace Sidvall.SystemEnvironment.Windows
{
    public class Package : IPackage
    {
        #region Public Members

        #region GetInstalledDateAsync

        public async Task<DateTime> GetInstalledDateAsync()
        {
            var assembly = System.Reflection.Assembly.GetEntryAssembly();
            var filePath = assembly.Location;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;
            byte[] b = new byte[2048];
            using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                stream.Read(b, 0, 2048);
            }
            int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
            int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
            var dt = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            dt = dt.AddSeconds(secondsSince1970);

            return await Task.FromResult(dt);
        }

        #endregion
        #region GetVersionAsync

        public Task<string> GetVersionAsync()
        {
            string version;

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                version = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            }
            else
            {
                var assembly = System.Reflection.Assembly.GetEntryAssembly();
                version = assembly.GetName().Version.ToString();
            }
            return Task.FromResult(version);
        }

        #endregion

        #region ToString

        public override string ToString()
        {
            return "Package - Windows";
        }

        #endregion

        #endregion
    }
}
